<?php

/*系统函数：filesize(),file_exists(),pathinfo(),unlink(),filemtime()
 * 获取文件信息	file_info($file_name)
 * 删除文件		del_file($file_name)
 * 删除文件夹 	del_dir($dir)
 * 复制文件		copy_file($file_name)
 * 移动文件		move_file($file_name)
 * 复制文件夹	copy_dir($dir)
 * 移动文件夹	move_dir($dir)
 * 创建文件夹	make_dir($directory,$mode = 0777)
 * 上传文件		upload_file($file,$maxSize=ini_get("upload_max_filesize"),$fileExtence=array())
 */

/**
 * 获取文件信息
 * $file_path ['dirname'];		//目录
 * $file_path ['basename'];		//文件名（含扩展名）
 * $file_path ['extension'];	//扩展名
 * $file_path ['filename'];		//文件名（不含扩展名，PHP>5.2）
 * @return array
 */
function file_info($file_name){
	if(file_exists($file_name))	{
		return pathinfo($file);
	}
}

/**
 * 删除文件
 * @return bool
 */
function del_file($file_name){
	if(file_exists($file_name))	{
		return @unlink($file_name) ? true : false;
	}	
}

/**
 * 删除文件夹
 * @return bool
 */
function del_dir($dir){
   $dh = opendir($dir);
    while ($file=readdir($dh)){
        if($file!="." && $file!=".."){
            $fullpath=$dir."/".$file;
            if(!is_dir($fullpath)){
                unlink($fullpath);
            } 
            else{
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    if(rmdir($dir)){
        return true;
    }
    else{
        return false;
    }
}

/**
 * 复制文件
 * @return bool
 */
function copy_file($file_name){
}
/**
 * 移动文件
 * @return bool
 */
function move_file($file_name){
}
/**
 * 复制文件夹
 * @return bool
 */
function copy_dir($dir){
}
/**
 * 移动文件夹
 * @return bool
 */
function move_dir($dir){
}




/**
 * 创建目录
 *
 * @param string $dir
 * @param int $mode
 * @return bool
 */
function mk_dir($dir, $mode = 0755)
{
    if (is_dir($dir) || @mkdir($dir, $mode))
        return true;
    if (! mk_dir(dirname($dir), $mode))
        return false;
    return @mkdir($dir, $mode);
}


/**
 * 创建文件夹
 * @param	string $s_type  
 * @param	int	文件夹权限
 * @return	bool
 */
function make_dir($directory,$mode = 0777) 
{
	if(@opendir($directory)){	
		return true;
	}
	else {	
		if (@mkdir($directory,$mode)) {		
			return true;
		} 
		else {		
			//try to repair the path
			$pathInfo = explode("/",$directory);
			$basedir="";

			foreach($pathInfo as $var) {			
				if ($var == ".") {				
					$basedir=$basedir."./";
					$begin = false;
				} 
				elseif ($var == ".."){ 				
					$basedir=$basedir."../";
					$begin = false;
				} 
				else {				
					if (!$begin){ 					
						$var = $var;
						$begin = true;
					}
					else{					
						$var = '/'.$var;
					}					
					if ($this->makeDir($basedir.$var,$mode)){ 					
						//echo "System Auto Repair ${basedir}${var} <br>";
						$repair = true;
						$basedir = $basedir.$var;
					}
					else {
						$repair = false;
					}
				}
			}
			return $repair;
		}
	}
}

/**
 * 上传文件
 * @param $file	string $s_type  
 * @return	bool
 */
function upload_file($file,$maxSize=2000000,$fileExtence=array()){
	$files     = $_FILES[$file];		
	$file_name = $files['name'];
	$file_type = $files['type'];
	$file_temp = $files['tmp_name'];
	
	
	$file_size = empty( $length ) ? ($files['size']+10) : $length;
	$file_error= $files['error'];
	
	if( !$this->isAllowType($file_name) || $file_size >$maxSize || $file_error != 0  ) {			
		return false;
	}
	else {		
		if (!empty($this->upload_dir) && !empty($this->upload_file_name)){			
			if ($this->makeDir($this->upload_dir,0755)){				
				$file_type = $this->getFileType($file_name);//设置文件类别
				$this->upload_file = $this->upload_file_name . '.' . $file_type;
				//return move_uploaded_file($file_temp , rtrim($this->upload_dir,'/') . '/' . $this->upload_file) ? true : false;
				move_uploaded_file($file_temp , rtrim($this->upload_dir,'/') . '/' . $this->upload_file) ? true : false;
				return $file_type;
			} 
			else return false;
		}
		else return false;
	}
}


function fotmat_bit($num)
{
    $bitunit = array(' B',' KB',' MB',' GB');
    for($key=0;$key<count($bitunit);$key++){
        if($num>=pow(2,10*$key)-1){ //1023B 会显示为 1KB
            $size=(ceil($num/pow(2,10*$key)*100)/100)." $bitunit[$key]";
        }
    }
    return $size;
}

function size_format( $bytes, $decimals = 0 ) {
	$quant = array(
		'TB' => 1099511627776,  // pow( 1024, 4)
		'GB' => 1073741824,     // pow( 1024, 3)
		'MB' => 1048576,        // pow( 1024, 2)
		'kB' => 1024,           // pow( 1024, 1)
		'B ' => 1,              // pow( 1024, 0)
	);
	foreach ( $quant as $unit => $mag )
		if ( doubleval($bytes) >= $mag )
			return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;

	return false;
}

/**
 * Test if a give filesystem path is absolute ('/foo/bar', 'c:\windows').
 *
 * @since 2.5.0
 *
 * @param string $path File path
 * @return bool True if path is absolute, false is not absolute.
 */
function path_is_absolute( $path ) {
	// this is definitive if true but fails if $path does not exist or contains a symbolic link
	if ( realpath($path) == $path )
		return true;

	if ( strlen($path) == 0 || $path[0] == '.' )
		return false;

	// windows allows absolute paths like this
	if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
		return true;

	// a path starting with / or \ is absolute; anything else is relative
	return (bool) preg_match('#^[/\\\\]#', $path);
}



function wp_ext2type( $ext ) {
	$ext2type = apply_filters( 'ext2type', array(
		'audio'       => array( 'aac', 'ac3',  'aif',  'aiff', 'm3a',  'm4a',   'm4b', 'mka', 'mp1', 'mp2',  'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
		'video'       => array( 'asf', 'avi',  'divx', 'dv',   'flv',  'm4v',   'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt',  'rm', 'vob', 'wmv' ),
		'document'    => array( 'doc', 'docx', 'docm', 'dotm', 'odt',  'pages', 'pdf', 'rtf', 'wp',  'wpd' ),
		'spreadsheet' => array( 'numbers',     'ods',  'xls',  'xlsx', 'xlsb',  'xlsm' ),
		'interactive' => array( 'key', 'ppt',  'pptx', 'pptm', 'odp',  'swf' ),
		'text'        => array( 'asc', 'csv',  'tsv',  'txt' ),
		'archive'     => array( 'bz2', 'cab',  'dmg',  'gz',   'rar',  'sea',   'sit', 'sqx', 'tar', 'tgz',  'zip' ),
		'code'        => array( 'css', 'htm',  'html', 'php',  'js' ),
	));
	foreach ( $ext2type as $type => $exts )
		if ( in_array( $ext, $exts ) )
			return $type;
}

function get_allowed_mime_types() {
	static $mimes = false;

	if ( !$mimes ) {
		// Accepted MIME types are set here as PCRE unless provided.
		$mimes = apply_filters( 'upload_mimes', array(
		'jpg|jpeg|jpe' => 'image/jpeg',
		'gif' => 'image/gif',
		'png' => 'image/png',
		'bmp' => 'image/bmp',
		'tif|tiff' => 'image/tiff',
		'ico' => 'image/x-icon',
		'asf|asx|wax|wmv|wmx' => 'video/asf',
		'avi' => 'video/avi',
		'divx' => 'video/divx',
		'flv' => 'video/x-flv',
		'mov|qt' => 'video/quicktime',
		'mpeg|mpg|mpe' => 'video/mpeg',
		'txt|asc|c|cc|h' => 'text/plain',
		'csv' => 'text/csv',
		'tsv' => 'text/tab-separated-values',
		'ics' => 'text/calendar',
		'rtx' => 'text/richtext',
		'css' => 'text/css',
		'htm|html' => 'text/html',
		'mp3|m4a|m4b' => 'audio/mpeg',
		'mp4|m4v' => 'video/mp4',
		'ra|ram' => 'audio/x-realaudio',
		'wav' => 'audio/wav',
		'ogg|oga' => 'audio/ogg',
		'ogv' => 'video/ogg',
		'mid|midi' => 'audio/midi',
		'wma' => 'audio/wma',
		'mka' => 'audio/x-matroska',
		'mkv' => 'video/x-matroska',
		'rtf' => 'application/rtf',
		'js' => 'application/javascript',
		'pdf' => 'application/pdf',
		'doc|docx' => 'application/msword',
		'pot|pps|ppt|pptx|ppam|pptm|sldm|ppsm|potm' => 'application/vnd.ms-powerpoint',
		'wri' => 'application/vnd.ms-write',
		'xla|xls|xlsx|xlt|xlw|xlam|xlsb|xlsm|xltm' => 'application/vnd.ms-excel',
		'mdb' => 'application/vnd.ms-access',
		'mpp' => 'application/vnd.ms-project',
		'docm|dotm' => 'application/vnd.ms-word',
		'pptx|sldx|ppsx|potx' => 'application/vnd.openxmlformats-officedocument.presentationml',
		'xlsx|xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml',
		'docx|dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml',
		'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
		'swf' => 'application/x-shockwave-flash',
		'class' => 'application/java',
		'tar' => 'application/x-tar',
		'zip' => 'application/zip',
		'gz|gzip' => 'application/x-gzip',
		'exe' => 'application/x-msdownload',
		// openoffice formats
		'odt' => 'application/vnd.oasis.opendocument.text',
		'odp' => 'application/vnd.oasis.opendocument.presentation',
		'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
		'odg' => 'application/vnd.oasis.opendocument.graphics',
		'odc' => 'application/vnd.oasis.opendocument.chart',
		'odb' => 'application/vnd.oasis.opendocument.database',
		'odf' => 'application/vnd.oasis.opendocument.formula',
		// wordperfect formats
		'wp|wpd' => 'application/wordperfect',
		) );
	}

	return $mimes;
}


/**
 * Determines if the blog can be accessed over SSL.
 *
 * Determines if blog can be accessed over SSL by using cURL to access the site
 * using the https in the siteurl. Requires cURL extension to work correctly.
 *
 * @since 2.5.0
 *
 * @param string $url
 * @return bool Whether SSL access is available
 */
function url_is_accessable_via_ssl($url)
{
	if (in_array('curl', get_loaded_extensions())) {
		$ssl = preg_replace( '/^http:\/\//', 'https://',  $url );

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $ssl);
		curl_setopt($ch, CURLOPT_FAILONERROR, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

		curl_exec($ch);

		$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close ($ch);

		if ($status == 200 || $status == 401) {
			return true;
		}
	}
	return false;
}

//function getType($file){
//	if(is_dir($file)){
//		$Type = 'DIR';
//	}
//	else{
//		preg_match  ("/^.+\.([a-z0-9]{0,})$/i",$this->File, $Ext);
//		switch(strtolower($Ext[1])){
//			case 'pcd'  :	case 'pcx'  :
//			case 'jpge' :	case 'jpg'  :	case 'jpe'  :
//			case 'gif'  :
//			case 'png'  :
//			case 'dib'  :	case 'rle'  :	case 'bmp'  :
//			case 'tiff'	:	case 'tif'  :
//				$Type = 'img';
//			break;
//
//			case 'vbs'  :	case 'vbse' :
//			case 'js'   :	case 'jse'  :
//				$Type = 'script';
//			break;
//
//			case 'exe'  :	case 'com' :
//				$Type = 'binary';
//			break;
//
//			case 'ra'   :	case 'rm'   :	case 'rmj'  :	case 'rms'  :	case 'rmi'	:
//			case 'ram'  :	case 'rmm'  :	case 'mnd'  :	case 'rp'   :	case 'rt'   :
//			case 'mp4'	:	case 'rmvb' :
//				$Type = 'realmedia';
//			break;
//
//			case 'mid'  :	case 'midi' :	case 'wav'  :	case 'wave' :
//			case 'avi'  :	case 'aiff' :	case 'asf'  :	case 'au'   :	case 'wma'  :
//			case 'mpeg'	:	case 'mpg'  :	case 'm3u'	:	case 'mov'  :
//				$Type = 'msmedia';
//			break;
//
//			case 'mp3'	:	case 'mp2'  :	case 'mpv'  :	case 'mx3'  :
//				$Type = 'mp3';
//			break;
//
//			case 'pdf'  :
//				$Type = 'pdf';
//			break;
//
//			case 'rar'  :	case 'arj'  :	case 'tar'  :	case 'ace'  :
//			case 'lzh'	:	case 'uue'  :	case 'bz2'  :
//				$Type = 'rar';
//			break;
//
//			case 'zip'  :	case 'gzip' :	case 'cab'  :
//			case 'tbz'  :	case 'tbz2' :
//				$Type = 'zip';
//			break;
//
//			case 'css'	:	case 'sql'  :	case 'txt'  :
//			case 'ini'	:	case 'inf'  :	case 'conf' :
//			case 'cgi'  :   case 'inc'  :	case 'csv'	:
//			case 'c'    :	case 'cpp'  :
//				$Type = 'text';
//			break;
//
//			case 'rtf'  :	case 'doc'  :
//				$Type = 'word';
//			break;
//
//			case 'swf'  :
//				$Type = 'flash';
//				break;
//
//			case 'php'  :	
//			case 'php3' :	
//			case 'phtml' :
//				$Type = 'php';
//				break;
//			case 'html' :	
//			case 'htm'  :	
//			case 'shtml' :
//				$Type = 'html';
//				break;
//			case 'xml'  :
//				$Type = 'xml';
//				break;
//			default     :
//				$Type = 'other';break;			
//		}
//	}
//	return $Type;
//}


function get_mode($file)
{
	$Mode = fileperms($file);
	if($Mode & 0x1000) $Type='p'; // FIFO pipe
	elseif($Mode & 0x2000) $Type='c'; // Character special
	elseif($Mode & 0x4000) $Type='d'; // Directory
	elseif($Mode & 0x6000) $Type='b'; // Block special
	elseif($Mode & 0x8000) $Type='-'; // Regular
	elseif($Mode & 0xA000) $Type='l'; // Symbolic Link
	elseif($Mode & 0xC000) $Type='s'; // Socket
	else $Type='u'; // UNKNOWN

	// Determine les permissions par Groupe
	$Owner['r'] = ($Mode & 00400) ? 'r' : '-';
	$Owner['w'] = ($Mode & 00200) ? 'w' : '-';
	$Owner['x'] = ($Mode & 00100) ? 'x' : '-';
	$Group['r'] = ($Mode & 00040) ? 'r' : '-';
	$Group['w'] = ($Mode & 00020) ? 'w' : '-';
	$Group['e'] = ($Mode & 00010) ? 'x' : '-';
	$World['r'] = ($Mode & 00004) ? 'r' : '-';
	$World['w'] = ($Mode & 00002) ? 'w' : '-';
	$World['e'] = ($Mode & 00001) ? 'x' : '-';

	// Adjuste pour SUID, SGID et sticky bit
	if( $Mode & 0x800 ) $Owner['e'] = ($Owner['e']=='x') ? 's' : 'S';
	if( $Mode & 0x400 ) $Group['e'] = ($Group['e']=='x') ? 's' : 'S';
	if( $Mode & 0x200 ) $World['e'] = ($World['e']=='x') ? 't' : 'T';
	
	$Mode = "$Type$Owner[r]$Owner[w]$Owner[e] $Group[r]$Group[w]$Group[e] $World[r]$World[w]$World[e]";
	return $Mode;
}



//兼容php4的file_put_contents
if(!function_exists('file_put_contents'))
{
    function file_put_contents($n, $d){
        $f=@fopen($n, "w");
        if (!$f){
            return FALSE;
        }
        else {
            fwrite($f, $d);
            fclose($f);
            return TRUE;
        }
    }
}


function write_log($s_log, $s_type = 'default', $s_level = 'log')
{
	$s_now_time = date('[y-m-d H:i:s]');
	$s_now_day  = date('Y_m_d');       
	$s_target   = DATA_LOG_PATH . $s_type . '/'; // 根据类型设置日志目标位置
	mk_dir($s_target, 0755);// 检查日志目录是否可写
	if (! is_writable($s_target)) exit('日志目录不可写!');        
	switch($s_level)// 分级写日志
	{
	    case 'error':
		$s_target .= 'Error_' . $s_now_day . '.log';
		break;
	    case 'warning':
		$s_target .= 'Warning_' . $s_now_day . '.log';
		break;
	    case 'notice':
		$s_target .= 'Notice_' . $s_now_day . '.log';
		break;
	    case 'debug':
		$s_target .= 'Debug_' . $s_now_day . '.log';
		break;
	    case 'info':
		$s_target .= 'Info_' . $s_now_day . '.log';
		break;
	    case 'cache':
		$s_target .= 'Cache_' . $s_now_day . '.log';
		break;
	    case 'db':
		$s_target .= 'Db_' . $s_now_day . '.log';
		break;
	    default:
		$s_target .= 'Log_' . $s_now_day . '.log';
		break;
	}
	//检测日志文件大小, 超过配置大小则重命名
	if (file_exists($s_target) && self::$i_log_size <= filesize($s_target)) {
	    $s_file_name = substr(basename($s_target), 0, strrpos(basename($s_target), '.log')) . '_' . time() . '.log';
	    rename($s_target, dirname($s_target) . DS . $s_file_name);
	}
	clearstatcache();// 写日志, 返回成功与否        
	return error_log("$s_now_time $s_log\n", 3, $s_target);
}

